<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

include 'Bot.php';
include 'RedmineApi.php';

$data = http_build_query(array(
   'ajax' => 1,
   'h' => 'd353c3ae22a25401d257643836d7231a9a95f953'
));

$opts = array(
    'http'=>array(
        'method'  => "GET",
        'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
    )
);

$context = stream_context_create($opts);

$data = file_get_contents('http://stage.fotostrana.ru/admin/staff/getStaffJson?' . $data, false, $context);
$uses = json_decode($data);

$usersBot = Bot::getInstance()->getUsers();

if (!$usersBot) {
    return false;
}

$insertBinds = array();
foreach ($uses as $userNew) {
    foreach ($usersBot as $userOld) {
        if (mb_strtolower($userNew->staff_redmine) == mb_strtolower($userOld['redmine_login']) && !$userOld['id']) {
            $bind = array(
                'name'     => $userNew->staff_name,
                'svn'      => $userNew->staff_svn,
                'skype'    => $userNew->staff_skype,
                'redmine'  => $userOld['id_redmine'],
                'playform' => preg_replace('/@.*/', '', $userNew->staff_playform),
            );
            $insertBinds[] = $bind;
        }

    }
}

if (!empty($insertBinds)) {
    $query = 'INSERT INTO `users` (`playform`, `skype`, `redmine`, `svn`, `name`) VALUES ';

    foreach ($insertBinds as $insertBind) {

        $query .= " ('{$insertBind['playform']}', '{$insertBind['skype']}', {$insertBind['redmine']}, '{$insertBind['svn']}', '{$insertBind['name']}'), ";
    }

    $insert = substr($query, 0, -2);
    var_dump($insert);
    Bot::getInstance()->execute($insert);
}
